import React from 'react';
import { forwardRef } from 'react';
import './index.scss';

export interface TableColumn {
  key: string;
  title: string;
  width?: number;
  align?: 'left' | 'center' | 'right';
  dataIndex: string;
  render?: (value: any, record: any, index: number) => React.ReactNode;
}

export interface TableRow {
  [key: string]: any;
}

export interface DataTableProps {
  width?: string | number;
  height?: string | number;
  headerBackgroundImage?: string;
  headerBackgroundColor?: string;
  rowBackgroundColor?: string;
  alternateRowBackgroundColor?: string;
  columns?: TableColumn[];
  dataSource?: TableRow[];
  headerHeight?: number;
  rowHeight?: number;
  maxRows?: number;
  showHeader?: boolean;
  headerTextColor?: string;
  rowTextColor?: string;
  headerFontSize?: number;
  rowFontSize?: number;
  headerFontWeight?: string | number;
  rowFontWeight?: string | number;
  columnSpacing?: number;
  showBorder?: boolean;
  borderColor?: string;
  hoverRowColor?: string;
  selectedRowColor?: string;
  emptyText?: string;
  loading?: boolean;
  onRowClick?: (record: TableRow, index: number) => void;
  onRowDoubleClick?: (record: TableRow, index: number) => void;
  onHeaderClick?: (column: TableColumn, index: number) => void;
  theme?: 'light' | 'dark';
  style?: React.CSSProperties;
  className?: string;
  onClick?: () => void;
  __designMode?: string;
  componentId?: string;
  _componentName?: string;
  forwardRef?: any;
}

const DataTable = forwardRef<HTMLDivElement, DataTableProps>((props, ref) => {
  const {
    width = 460,
    height = 'auto',
    headerBackgroundImage = 'http://localhost:8085/static/images/qixiangfangzhai/bz54.png',
    headerBackgroundColor = 'rgba(0,0,0,0.3)',
    rowBackgroundColor = 'transparent',
    alternateRowBackgroundColor = 'rgba(16,85,163,0.18)',
    columns = [
      {
        key: 'level',
        title: '天气预警等级',
        width: 96,
        align: 'center',
        dataIndex: 'level'
      },
      {
        key: 'name',
        title: '预警名称',
        width: 168,
        align: 'center',
        dataIndex: 'name'
      },
      {
        key: 'time',
        title: '预警发布时间',
        width: 128,
        align: 'center',
        dataIndex: 'time'
      }
    ],
    dataSource = [
      {
        key: '1',
        level: 'IV级',
        name: '杭州市临平区气象台发布…',
        time: '2025-05-09 04:00:00'
      },
      {
        key: '2',
        level: 'IV级',
        name: '杭州市临平区气象台发布…',
        time: '2025-05-09 04:00:00'
      }
    ],
    headerHeight = 40,
    rowHeight = 40,
    maxRows = 10,
    showHeader = true,
    headerTextColor = '#56A5FF',
    rowTextColor = 'rgba(255,255,255,0.9)',
    headerFontSize = 16,
    rowFontSize = 14,
    headerFontWeight = 500,
    rowFontWeight = 400,
    columnSpacing = 0,
    showBorder = false,
    borderColor = 'rgba(255,255,255,0.1)',
    hoverRowColor = 'rgba(86,165,255,0.2)',
    selectedRowColor = 'rgba(86,165,255,0.3)',
    emptyText = '暂无数据',
    loading = false,
    onRowClick,
    onRowDoubleClick,
    onHeaderClick,
    theme = 'dark',
    style = {},
    className = '',
    onClick,
    __designMode,
    componentId,
    _componentName,
    forwardRef: forwardRefProp,
    ...otherProps
  } = props;

  const [selectedRowIndex, setSelectedRowIndex] = React.useState<number | null>(null);

  const componentStyle: React.CSSProperties = {
    width: typeof width === 'number' ? `${width}px` : width,
    height: typeof height === 'number' ? `${height}px` : height,
    '--header-bg-color': headerBackgroundColor,
    '--row-bg-color': rowBackgroundColor,
    '--alt-row-bg-color': alternateRowBackgroundColor,
    '--hover-row-color': hoverRowColor,
    '--selected-row-color': selectedRowColor,
    '--border-color': borderColor,
    '--column-spacing': `${columnSpacing}px`,
    ...style
  } as React.CSSProperties;

  const handleRowClick = (record: TableRow, index: number) => {
    setSelectedRowIndex(index);
    if (onRowClick) {
      onRowClick(record, index);
    }
  };

  const handleRowDoubleClick = (record: TableRow, index: number) => {
    if (onRowDoubleClick) {
      onRowDoubleClick(record, index);
    }
  };

  const handleHeaderClick = (column: TableColumn, index: number) => {
    if (onHeaderClick) {
      onHeaderClick(column, index);
    }
  };

  const renderCellContent = (column: TableColumn, record: TableRow, rowIndex: number) => {
    const value = record[column.dataIndex];
    if (column.render) {
      return column.render(value, record, rowIndex);
    }
    return value;
  };

  const displayDataSource = maxRows ? dataSource.slice(0, maxRows) : dataSource;

  const dataTableClassName = ['data-table', theme, className].filter(Boolean).join(' ');

  if (loading) {
    return (
      <div
        ref={ref}
        className={`${dataTableClassName} loading`}
        style={componentStyle}
        onClick={onClick}
        data-component-id={componentId}
        data-component-name={_componentName}
        data-design-mode={__designMode}
        {...otherProps}
      >
        <div className="loading-content">
          <div className="loading-spinner"></div>
          <span>加载中...</span>
        </div>
      </div>
    );
  }

  return (
    <div
      ref={ref}
      className={dataTableClassName}
      style={componentStyle}
      onClick={onClick}
      data-component-id={componentId}
      data-component-name={_componentName}
      data-design-mode={__designMode}
      {...otherProps}
    >
      {/* 表头 */}
      {showHeader && (
        <div 
          className="table-header"
          style={{
            height: `${headerHeight}px`,
            backgroundImage: headerBackgroundImage ? `url(${headerBackgroundImage})` : undefined
          }}
        >
          {columns.map((column, index) => (
            <div
              key={column.key}
              className={`header-cell ${column.align || 'center'}`}
              style={{
                width: column.width ? `${column.width}px` : 'auto',
                color: headerTextColor,
                fontSize: `${headerFontSize}px`,
                fontWeight: headerFontWeight,
                marginRight: index < columns.length - 1 ? `${columnSpacing}px` : 0
              }}
              onClick={() => handleHeaderClick(column, index)}
            >
              {column.title}
            </div>
          ))}
        </div>
      )}

      {/* 表体 */}
      <div className="table-body">
        {displayDataSource.length > 0 ? (
          displayDataSource.map((record, rowIndex) => (
            <div
              key={record.key || rowIndex}
              className={`table-row ${selectedRowIndex === rowIndex ? 'selected' : ''}`}
              style={{
                height: `${rowHeight}px`,
                backgroundColor: rowIndex % 2 === 1 ? alternateRowBackgroundColor : rowBackgroundColor
              }}
              onClick={() => handleRowClick(record, rowIndex)}
              onDoubleClick={() => handleRowDoubleClick(record, rowIndex)}
            >
              {columns.map((column, colIndex) => (
                <div
                  key={column.key}
                  className={`table-cell ${column.align || 'center'}`}
                  style={{
                    width: column.width ? `${column.width}px` : 'auto',
                    color: rowTextColor,
                    fontSize: `${rowFontSize}px`,
                    fontWeight: rowFontWeight,
                    marginRight: colIndex < columns.length - 1 ? `${columnSpacing}px` : 0
                  }}
                >
                  {renderCellContent(column, record, rowIndex)}
                </div>
              ))}
            </div>
          ))
        ) : (
          <div className="empty-state">
            <span className="empty-text">{emptyText}</span>
          </div>
        )}
      </div>
    </div>
  );
});

DataTable.displayName = 'DataTable';

export default DataTable; 